/**
 * Copyright (C), -2025, www.bosssof.com.cn
 * @FileName DictionaryServiceImpl.java
 * @Author Administrator
 * @Date 2023-02-22  13:51
 * @Description 提供业务字典服务
 * History:
 * <author> Administrator
 * <time> 2023-02-22  13:51
 * <version> 1.0.0
 * <desc> 初始化
 */
package com.sd365.permission.centre.service.impl;

import com.github.pagehelper.Page;
import com.sd365.common.core.annotation.mybatis.Pagination;
import com.sd365.common.core.annotation.stuffer.CommonFieldStuffer;
import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.annotation.stuffer.MethodTypeEnum;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.common.exception.code.BizErrorCode;
import com.sd365.common.core.common.service.AbstractBusinessService;
import com.sd365.common.util.BeanException;
import com.sd365.common.util.BeanUtil;
import com.sd365.permission.centre.dao.mapper.DictionaryMapper;
import com.sd365.permission.centre.entity.Dictionary;
import com.sd365.permission.centre.pojo.dto.CompanyDTO;
import com.sd365.permission.centre.pojo.dto.DictionaryDTO;
import com.sd365.permission.centre.pojo.dto.DictionaryTypeDTO;
import com.sd365.permission.centre.pojo.dto.OrganizationDTO;
import com.sd365.permission.centre.pojo.query.DictionaryQuery;
import com.sd365.permission.centre.service.DictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @class DictionaryServiceImpl
 * @classdesc  业务字典的服务类，系统中其他表依赖字典表的字典数字
 * @author Administrator
 * @date 2020-10-18  18:00
 * @version 1.0.0
 */
@Service
public class DictionaryServiceImpl extends AbstractBusinessService implements DictionaryService {
    /**
     *  字典dao类
     */
    @Autowired
    private DictionaryMapper dictionaryMapper;
    /**
     *  雪花算法的id生成器
     */
    @Autowired
    private IdGenerator idGenerator;


    @CommonFieldStuffer(methodType = MethodTypeEnum.ADD)
    @Override
    public Boolean add(@NotNull @Valid  DictionaryDTO dictionaryDTO) {
        // 先业务检查 如果业务检查没有通过则抛出异常
        if(!CollectionUtils.isEmpty(dictionaryMapper.selectByName(dictionaryDTO.getName()))){
            throw new  BusinessException(BizErrorCode.DATA_INSERT_FOUND_NO_UNIQUE_RECORD);
        }
        // 开始准备插入字典数据
        Dictionary dictionary=BeanUtil.copy(dictionaryDTO,Dictionary.class);
        dictionary.setId(idGenerator.snowflakeId());
        dictionary.setDictionaryTypeId(dictionaryDTO.getDictionaryTypeDTO().getId());
        super.baseDataStuff4Add(dictionary);
        return dictionaryMapper.insert(dictionary)>0;
    }

    @Override
    public Boolean remove(@NotNull  Long id, @NotNull  Long version) {
        Example example=new Example(Dictionary.class);
        example.createCriteria().andEqualTo("id",id).andEqualTo("version",version);
        return dictionaryMapper.deleteByExample(example)>0;
    }

    @Override
    public Boolean modify(@NotNull @Valid  DictionaryDTO dictionaryDTO) {
        //  系统要做业务前置条件检查
        if(!CollectionUtils.isEmpty(dictionaryMapper.selectByName(dictionaryDTO.getName()))){
            throw new  BusinessException(BizErrorCode.DATA_UPDATE_DUE_DUPLICATE_RECORD);
        }
        // 开始执行修改
        Dictionary dictionary= BeanUtil.copy(dictionaryDTO, Dictionary.class);
        dictionary.setValue(dictionaryDTO.getName());
        super.baseDataStuff4Updated(dictionary);
        return dictionaryMapper.updateDictionary(dictionary)>0;
    }

    @Pagination
    @CommonFieldStuffer(methodType = MethodTypeEnum.QUERY)
    @Override
    public List<DictionaryDTO> commonQuery(@NotNull DictionaryQuery dictionaryQuery) {
                // 准备查询条件
                Dictionary dictionary = new Dictionary();
                dictionary.setName(dictionaryQuery.getName());
                dictionary.setDictionaryTypeId(dictionaryQuery.getDictionaryCategoryId());
                // 查询到dictionarylist 将其转换位 dictionaryDTOList 返回
                List<Dictionary> dictionaryList=dictionaryMapper.commonQuery(dictionary);
                setPageInfo2BaseContextHolder((Page)dictionaryList);
                return  BeanUtil.copyList(dictionaryList, DictionaryDTO.class, new BeanUtil.CopyCallback() {
                    @Override
                    public void copy(Object o, Object o1) {
                        // 调用 BeanUtil.copyProperties
                        if (o == null || o1 == null)
                            throw new BeanException("拷贝对象不可以为空", new Exception("copyList 拷贝回调错误"));
                        Dictionary dictionarySource = (Dictionary) o;
                        DictionaryDTO dictionaryDTO = (DictionaryDTO) o1;
                        BeanUtil.copy(dictionarySource.getCompany(), dictionaryDTO.getCompanyDTO(),CompanyDTO.class);
                        BeanUtil.copy(dictionarySource.getOrganization(), dictionaryDTO.getOrganizationDTO(),OrganizationDTO.class);
                        BeanUtil.copy(dictionarySource.getDictionaryType(), dictionaryDTO.getDictionaryTypeDTO(), DictionaryTypeDTO.class);
                    }
                });
    }

    @Override
    public DictionaryDTO queryById( @NotNull  Long id) {
            DictionaryDTO dictionaryDTO= new DictionaryDTO();
            Dictionary dictionary=dictionaryMapper.selectById(id);
            if(dictionary!=null) {
                dictionaryDTO= BeanUtil.copy(dictionary,DictionaryDTO.class);
                BeanUtil.copy(dictionary.getCompany(),dictionaryDTO.getCompanyDTO(), CompanyDTO.class);
                BeanUtil.copy(dictionary.getOrganization(),dictionaryDTO.getOrganizationDTO(), OrganizationDTO.class);
                BeanUtil.copy(dictionary.getDictionaryType(),dictionaryDTO.getDictionaryTypeDTO(), DictionaryTypeDTO.class);
            }
            return dictionaryDTO;
    }

    @Override
    public List<DictionaryDTO> queryByTypeId(@NonNull Long id) {
            List<Dictionary> dictionarys = dictionaryMapper.selectByTypeId(id);
            //对象转化 po list to dto list
            return  BeanUtil.copyList(dictionarys, DictionaryDTO.class, new BeanUtil.CopyCallback() {
                @Override
                public void copy(Object o, Object o1) {
                    // 调用 BeanUtil.copyProperties
                    if (o == null || o1 == null)
                        throw new BeanException("拷贝对象不可以为空", new Exception("copyList 拷贝回调错误"));
                    Dictionary dictionarySource = (Dictionary) o;
                    DictionaryDTO dictionaryDTO = (DictionaryDTO) o1;
                    BeanUtil.copy(dictionarySource.getCompany(), dictionaryDTO.getCompanyDTO(),CompanyDTO.class);
                    BeanUtil.copy(dictionarySource.getOrganization(), dictionaryDTO.getOrganizationDTO(),OrganizationDTO.class);
                    BeanUtil.copy(dictionarySource.getDictionaryType(), dictionaryDTO.getDictionaryTypeDTO(),DictionaryTypeDTO.class);
                }
            });
    }

    @Override
    public Boolean batchUpdate(@NotEmpty DictionaryDTO[] dictionaryDTOS) {
        /**
         * 批量更新接口依据id和版本如果某条则回滚，如果同时有人更导致我们更新失败
         */
        for(DictionaryDTO dictionaryDTO:dictionaryDTOS){
            Dictionary dictionary=BeanUtil.copy(dictionaryDTO,Dictionary.class);
            Example example=new Example(dictionary.getClass());
            dictionary.setVersion(ObjectUtils.isEmpty(dictionaryDTO.getVersion()) ? 0 :dictionaryDTO.getVersion()+1);
            example.createCriteria().andEqualTo("id",dictionary.getId()).andEqualTo("version",dictionaryDTO.getVersion());;
            super.baseDataStuff4Updated(dictionary);
            // 如果有一条没更新成功则回滚全部
            if(dictionaryMapper.updateByExampleSelective(dictionary,example)<=0){
                throw new BusinessException(BizErrorCode.DATA_UPDATE_RETURB_EFFECT_LATTER_ZERO);

            }
        }
        return true;
    }

    @Override
    public Boolean batchRemove(@NotEmpty DictionaryDTO[] dictionaryDTOS) {
        for (DictionaryDTO dictionaryDTO : dictionaryDTOS) {
            Example example = new Example(Dictionary.class);
            example.createCriteria().andEqualTo("id", dictionaryDTO.getId()).andEqualTo("version", dictionaryDTO.getVersion());
            if (dictionaryMapper.deleteByExample(example) <= 0) {
                throw new BusinessException(BizErrorCode.DATA_DELETE_NOT_FOUND, new Exception("删除的" + dictionaryDTO.getId() + "记录有匹配到版本"));
            }
        }
        return true;
    }
}
